import React, {useState, useEffect} from 'react'

import {Card, Button, Popconfirm, Modal, Form, Input, Switch, List, Avatar, message, Tag, Empty, Tooltip } from 'antd'

import { VerticalAlignBottomOutlined, VerticalAlignTopOutlined, FileAddOutlined, CloseOutlined, CheckOutlined, LikeOutlined, RotateLeftOutlined, RedEnvelopeTwoTone, StarOutlined, LikeTwoTone } from '@ant-design/icons'

import {Container, ProjectItem, NearPlanItem} from './style'

import {baseUrl} from '../../../https'

import WorkplaceRequest from '../../../request/workplace_request'
import ArticleRequest from '../../../request/article_request'

import getDateText from '../../../assets/js/getTimeText'

import {connect} from 'react-redux'
import {changeIsOpen} from '../../../store/actionCreators'

const workplace_request = new WorkplaceRequest()
const article_request = new ArticleRequest()

let clickLinkState = true //点击链接状态

function Workplace(props){
    const {isOpen, changeIsOpen} = props //是否展开全部收藏
    const [form] = Form.useForm()
    const gridStyle = {
        width: 1 / 3 * 100 + '%',
        textAlign: 'center'
    }
    const layout = {
        labelCol: { span: 6 },
        wrapperCol: { span: 16 },
    };
    const colorList = {
        ad: 'linear-gradient(45deg, #ffc069, #d46b08)', //广告色
        excellent: 'linear-gradient(45deg, #ffa39e, #cf1322)', //精品推荐
        collection: 'linear-gradient(45deg, #40a9ff, #0050b3)' //收藏
    }
    const [projectList, setProjectList] = useState([]) //6个
    const [projectAllList, setProjectAllList] = useState([]) //全部收藏

    const [documentList, setDocumentList] = useState([])

    const [nearPlanList, setNearPlanList] = useState([
        {
            content: '这是一个当前非常流行的响应式的前端框架'
        },
        {
            content: '这是一个当前非常流行的响应式的前端框架'
        },
        {
            content: '这是一个当前非常流行的响应式的前端框架'
        },
        {
            content: '这是一个当前非常流行的响应式的前端框架'
        }
    ])

    const [commonPlanAreaList, setCommonPlanAreaList] = useState([
        {
            name: '小丽',
            state: '发布',
            plan: '改善生活水平，提高幸福感',
            time: undefined
        },
        {
            name: '小丽',
            state: '发布',
            plan: '改善生活水平，提高幸福感',
            time: undefined
        },
        {
            name: '小丽',
            state: '发布',
            plan: '改善生活水平，提高幸福感',
            time: undefined
        },
        {
            name: '小丽',
            state: '发布',
            plan: '改善生活水平，提高幸福感',
            time: undefined
        }
    ])

    const [addDocumentVisible, setAddDocumentVisible] = useState(false)
    const [addDocumentLoading, setAddDocumentLoading] = useState(false)

    const [record, setRecord] = useState('') //随笔记录
    const [recordLoading, setRecordLoading] = useState(false)

    const [appreciateVisible, setAppreciateVisible] = useState(false)

    useEffect(() => {
        getRecord()
        getLink()
        getCollectList()
    }, [])

    const getCollectList = () => {
        workplace_request.getCollectList({
            isTop: '1'
        }).then(res => {
            if(res.length > 6){
                setProjectList(res.slice(0, 6))
            }else{
                setProjectList(res || [])
            }
            setProjectAllList(res || [])
        })
    }

    const collectArticle = (id, title, desc) => {
        article_request.collectArticle({
            id,
            title,
            desc
        }).then(res => {
            message.success('已加入收藏')
        })
    }

    const appreciateArticle = () => {
        setAppreciateVisible(true)
    }

    const moveCollect = (id) => {
        workplace_request.moveCollect({
            id
        }).then(res => {
            res && message.success(res)
            getCollectList()
        })
    }
    const likeArticle = (id) => {
        article_request.likeArticle({
            id
        }).then(res => {
            getCollectList()
        })
    }

    const handleaddDocumentOk = () => {
        setAddDocumentLoading(true)
        workplace_request.addLink({
            title: form.getFieldValue('documentName'),
            path: form.getFieldValue('documentLink')
        }).then(res => {
            message.success('新增链接成功！')
            getLink()
            setAddDocumentLoading(false)
            setAddDocumentVisible(false)
            form.setFieldsValue({
                documentName: '',
                documentLink: ''
            })
        })
    }

    const handleaddDocumentCancel = () => {
        setAddDocumentVisible(false)
        form.setFieldsValue({
            documentName: '',
            documentLink: ''
        })
    }

    //获取随笔记录
    const getRecord = () => {
        workplace_request.getRecord().then(res => {
            setRecord(res)
        })
    }

    //保存随笔记录
    const saveRecord = () => {
        setRecordLoading(true)
        workplace_request.saveRecord({
            content: record
        }).then(res => {
            message.success('随笔记录保存成功！')
        }).finally(() => {
            setRecordLoading(false)
        })
    }

    //获取常用链接
    const getLink = () => {
        workplace_request.getLink().then(res => {
            setDocumentList(res)
        })
    }
    const deletLink = (id) => {
        workplace_request.deleteLink({
            id
        }).then(res => {
            message.success('删除链接成功！')
            getLink()
        })
    }
    const clickLink = (id) => { //30秒内只能触发一次
        if(clickLinkState){
            workplace_request.visitLink({
                id
            }).then(res => {
                clickLinkState = false
                setTimeout(() => {
                    clickLinkState = true
                }, 30 * 1000)
            })
        }
    }

    const goToCollect = (id) => {
        window.open(window.location.origin + '/article/detail/' + id)
    }
    return (
        <Container>
            <div className="left">
                <Card title="优质收藏" bordered={false} style={{ marginBottom: 24}} extra={<Button icon={!isOpen ? <VerticalAlignBottomOutlined /> : <VerticalAlignTopOutlined />} type="link" onClick={() => changeIsOpen(!isOpen)}>{isOpen ? '收起' : '展开'}</Button>}>
                    {
                        (isOpen ? projectAllList : projectList).map((item, index) => {
                            return (
                                <Card.Grid style={gridStyle} key={index}>
                                    <ProjectItem>
                                        <div className="top" onClick={() => goToCollect(item.articleid)}>
                                            <div className="avatar" style={{background: colorList[item.type]}}>{item.type === 'ad' ? '荐' : item.type === 'excellent' ? '精' : item.title.substring(0, 1).toUpperCase()}</div>
                                            <span>{item.title}</span>
                                        </div>
                                        <div className="desc" onClick={() => goToCollect(item.articleid)}>
                                            {item.desc.length < 28 ? item.desc : (item.desc.substring(0, 28) + '...')}
                                        </div>
                                        <div className="footer">
                                            {
                                                item.type === 'collection' ? 
                                                <React.Fragment>
                                                    <Tooltip title="从工作台移除" placement="bottom">
                                                        <RotateLeftOutlined onClick={() => moveCollect(item.articleid)}/>
                                                    </Tooltip>
                                                    {
                                                        !item.isLike ? 
                                                        <Tooltip title="喜欢" placement="bottom">
                                                            <LikeOutlined onClick={() => likeArticle(item.articleid)}/>
                                                        </Tooltip>
                                                        :
                                                        <Tooltip title="不爱了" placement="bottom">
                                                            <LikeTwoTone twoToneColor="#eb2f96" onClick={() => likeArticle(item.articleid)}/>
                                                        </Tooltip>
                                                    }
                                                </React.Fragment>
                                                : item.type === 'excellent' ?
                                                <Tooltip title="收藏" placement="bottom">
                                                    <StarOutlined onClick={() => collectArticle(item.articleid, item.title, item.desc)}/>
                                                </Tooltip>
                                                : ''
                                            }
                                            {
                                                item.type === 'ad' ? 
                                                <div className="author">
                                                    <span>作者：{item.author}</span>
                                                </div> :
                                                <Tooltip title="赞赏作者" placement="bottom">
                                                    <RedEnvelopeTwoTone twoToneColor="#faad14" onClick={appreciateArticle}/>
                                                </Tooltip>
                                            }
                                        </div>
                                    </ProjectItem>
                                </Card.Grid>
                            )
                        })
                    }
                </Card>
                <Card title="计划公屏" bordered={false} style={{ marginBottom: 24}}>
                    <List
                        itemLayout="horizontal"
                        dataSource={commonPlanAreaList}
                        renderItem={item => (
                        <List.Item>
                            <List.Item.Meta
                            avatar={<Avatar src={require("../../../assets/img/avatar.png")} />}
                            title={<span><a href="https://ant.design">{item.name}</a> <span>{item.state}了计划</span> <a href="https://ant.design">《{item.plan}》</a></span>}
                            description={getDateText(item.time)}
                            />
                        </List.Item>
                        )}
                    />
                </Card>
            </div>
            <div className="right">
                <Card title="常用链接" bordered={false} style={{ marginBottom: 24}} bodyStyle={{paddingBottom: 16}} extra={<Button onClick={() => setAddDocumentVisible(true)} icon={<FileAddOutlined />} type="link">添加</Button>}>
                    {
                        documentList.length === 0 ? 
                        <Empty description={false} /> :
                        documentList.map((item, index) => {
                            return (
                                <Tag className="document-item" key={index} color={item.isTop ? 'warning' : ''}>
                                    <a href={item.path} target="_blank" onClick={() => clickLink(item.id)}>{item.title}</a>
                                    <Popconfirm
                                        title={"确定删除【" + item.title + "】快捷入口?"}
                                        okText="删除"
                                        cancelText="取消"
                                        onConfirm={() => deletLink(item.id)}
                                    >
                                        <CloseOutlined className="delete-document" />
                                    </Popconfirm>
                                </Tag>
                            )
                        })
                    }  
                </Card>
                <Card title="近期计划" bordered={false} style={{ marginBottom: 24}}>
                    {
                        nearPlanList.map((item, index) => {
                            return (
                                <NearPlanItem key={index}>
                                    <span className="plan-content">{item.content}</span>
                                    <Switch
                                        checkedChildren={<CheckOutlined />}
                                        unCheckedChildren={<CloseOutlined />}
                                        size="small"
                                    />
                                </NearPlanItem>
                            )
                        })
                    }
                </Card>
                <Card title="随笔记录" bordered={false} style={{ marginBottom: 24}} extra={<Button loading={recordLoading} size="small" type="primary" onClick={saveRecord}>保存</Button>}>
                    <Input.TextArea style={{color: 'black'}} placeholder="随便写点儿什么吧~" value={record} onChange={(e) => setRecord(e.target.value)} autoSize={{ minRows: 4, maxRows: 6 }} maxLength={500}></Input.TextArea>
                </Card>
            </div>
            <Modal
                title="添加常用链接"
                visible={addDocumentVisible}
                onOk={handleaddDocumentOk}
                onCancel={handleaddDocumentCancel}
                confirmLoading={addDocumentLoading}
                okText="确认添加"
            >
                <Form
                    {...layout}
                    form={form}
                >
                    <Form.Item
                        label="链接名称"
                        name="documentName"
                        rules={[{ required: true, message: '请输入链接名称!' }]}
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item
                        label="链接路径"
                        name="documentLink"
                        rules={[{ required: true, message: '请输入链接路径!' }]}
                    >
                        <Input />
                    </Form.Item>
                </Form>
            </Modal>
            <Modal
                visible={appreciateVisible}
                title="微信赞赏码"
                footer={null}
                width="360px"
                onCancel={() => setAppreciateVisible(false)}
            >
                <img src={require("../../../assets/img/zanshang.jpg")} style={{width: '100%'}} alt=""/>
            </Modal>
        </Container>
    )
}

const mapState = (state) => ({
    isOpen: state.isOpen
})

const mapDispatch = (dispatch) => ({
    changeIsOpen(data){
		dispatch(changeIsOpen(data))
	}
})

export default connect(mapState, mapDispatch)(Workplace)